package cn.dgut.training.service;

import cn.dgut.training.config.AliyunConfig;
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSSClient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Service
public class FileUploadService {


    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};

    @Autowired
    private  OSSClient ossClient;

    @Autowired
    private   AliyunConfig aliyunConfig;

    /**
     *@Description  上传成功返回true，否则返回false
     *@Param  [uploadFile]
     *@Return  boolean
     */
    public  String upload(MultipartFile uploadFile) {


        //1.图片做校验，对后缀名
        boolean isLegal = false;

        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }

        if (!isLegal) {
            return "";
        }

        //2.文件新路径

        String fileName = uploadFile.getOriginalFilename();

        String filePath = getFilePath(fileName);

        //3.上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //4.1上传失败
            return "";
        }

        //4.2上传成功
        return  aliyunConfig.getUrlPrefix() + "/"+filePath;

    }

    private  String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();

        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
